package com.yxuan.springboot.controller;

import com.yxuan.springboot.model.Goods;
import com.yxuan.springboot.model.Orders;
import com.yxuan.springboot.model.UserLogin;
import com.yxuan.springboot.model.UserVip;
import com.yxuan.springboot.service.GoodsService;
import com.yxuan.springboot.service.OrdersService;
import com.yxuan.springboot.service.UserLoginService;
import com.yxuan.springboot.service.UserVipService;
import com.yxuan.springboot.util.ResolveTokenUtil;
import com.yxuan.springboot.util.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;

/**
 * 
 * @author zchao
 *   UserVip控制器
 * @date 2023-05-09 11:20:06
 */
@Controller
@Api(tags = "用户会员表")
@RequestMapping(value = "/uservip", method = {RequestMethod.POST,RequestMethod.GET})
public class UserVipController extends BaseController<UserVip>{


	@Autowired
    private UserVipService userVipService;

	@Autowired
    private OrdersService ordersService;

	@Autowired
    private GoodsService goodsService;

    @Autowired
    private UserLoginService userLoginService;

    //用户查看vip等级
    @ResponseBody
    @RequestMapping("/findVipRank")
    public Result findVipRank(HttpServletRequest request) throws Exception {

        HashMap<String, Object> map = new HashMap<>();

        UserLogin userLogin = ResolveTokenUtil.targetLogin(request.getHeader("token"));
        UserLogin targetUserLogin = userLoginService.findObjectByPramas(userLogin);
        UserVip userVip = new UserVip();
        userVip.setUserId(targetUserLogin.getId());
        UserVip targetUserVip = userVipService.findObjectByPramas(userVip);

        map.put("vipRank",targetUserVip.getVipRank());

        return new Result(map,SUCCESSCODE,"查询vip等级成功");

    }


    @ResponseBody
    @ApiOperation(value = "根据分数，意向省份查询该分数对应排名，最终返回院校信息", notes = "根据分数，意向省份查询该分数对应排名院校信息")
    @RequestMapping("/changeVipInfor")
    public UserVip changeVipInfor(String orderId,String userLoginId) throws Exception {
        Orders orders = new Orders();
        orders.setOrderId(orderId);
        orders.setOrdersState("1");
//        修改订单状态
        ordersService.upd(orders);

        Orders orders1 = ordersService.findObjectByPramas(orders);
//      搜索该商品的名称
        Goods goods = new Goods();
        goods.setId(Integer.valueOf(orders1.getGoodsId()));
        Goods goods1 = goodsService.findObjectByPramas(goods);

        UserVip userVip = new UserVip();
        userVip.setUserId(Integer.valueOf(userLoginId));
        UserVip userVip1 = userVipService.findObjectByPramas(userVip);

        Integer getGptTimes = 0;
        if(userVip1.getGptTimes() == null || userVip1.getGptTimes().equals("")){
            getGptTimes = 0;
        }else{
            getGptTimes = Integer.valueOf(userVip1.getGptTimes());
        }

        Integer getInfoUpdTimes = 0;
        if(userVip1.getInfoUpdTimes() == null || userVip1.getInfoUpdTimes().equals("")){
            getInfoUpdTimes = 0;
        }else{
            getInfoUpdTimes = Integer.valueOf(userVip1.getInfoUpdTimes());
        }

        Integer getProbabilityTimes = 0;
        if(userVip1.getProbabilityTimes() == null || userVip1.getProbabilityTimes().equals("")){
            getProbabilityTimes = 0;
        }else{
            getProbabilityTimes = Integer.valueOf(userVip1.getProbabilityTimes());
        }
        switch (goods1.getName()) {
            case "日会员":
                userVip.setVipRank("1");
                userVip.setProbabilityTimes(String.valueOf(getProbabilityTimes + 50));
                userVip.setInfoUpdTimes(String.valueOf(getInfoUpdTimes + 2));
                userVip.setGptTimes(String.valueOf(getGptTimes + 5));
                break;
            case "周会员":
                userVip.setVipRank("2");
                userVip.setProbabilityTimes(String.valueOf(getProbabilityTimes + 50));
                userVip.setInfoUpdTimes(String.valueOf(getInfoUpdTimes + 3));
                userVip.setGptTimes(String.valueOf(getGptTimes + 50));
                break;
            case "月会员":
                userVip.setVipRank("3");
                userVip.setProbabilityTimes(String.valueOf(getProbabilityTimes + 50));
                userVip.setInfoUpdTimes(String.valueOf(getInfoUpdTimes + 5));
                userVip.setGptTimes(String.valueOf(getGptTimes + 120));
                break;
            default:
                userVip.setVipRank("1");
                userVip.setProbabilityTimes(String.valueOf(getProbabilityTimes + 50));
                userVip.setInfoUpdTimes(String.valueOf(getInfoUpdTimes + 2));
                userVip.setGptTimes(String.valueOf(getGptTimes + 5));
                break;
        }
        Date nows = new Date(System.currentTimeMillis());

        if(userVip1.getExpirationTime() == null || userVip1.getExpirationTime().compareTo(nows) < 0){
            LocalDateTime now = LocalDateTime.now();
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            String formattedNow = now.format(formatter);
            System.out.println("当前时间：" + formattedNow);
            LocalDateTime after10Minutes = null;
            if(goods1.getName().equals("日会员")){
                 after10Minutes = now.plusMinutes(60*24);

            }else if(goods1.getName().equals("周会员")){
                 after10Minutes = now.plusMinutes(60*24*7);

            }else if(goods1.getName().equals("月会员")){
                 after10Minutes = now.plusMinutes(60*24*30);

            }else{
                 after10Minutes = now.plusMinutes(60*24);

            }
            String formattedAfter10Minutes =  after10Minutes.format(formatter);
            Date expirationTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(formattedAfter10Minutes);
            userVip.setExpirationTime(expirationTime);
        }else{
            Date date = userVip1.getExpirationTime();

            // 使用Calendar类将date转换为Calendar对象
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(date);

            // 在Calendar对象上增加24小时


            if(goods1.getName().equals("日会员")){
                calendar.add(Calendar.HOUR_OF_DAY, 24);
            }else if(goods1.getName().equals("周会员")){
                calendar.add(Calendar.HOUR_OF_DAY, 24*7);
            }else if(goods1.getName().equals("月会员")){
                calendar.add(Calendar.HOUR_OF_DAY, 24*31);
            }else{
                calendar.add(Calendar.HOUR_OF_DAY, 24);
            }
            // 将Calendar对象转换为Date对象
            Date newDate = calendar.getTime();

            // 使用DateTimeFormatter类将Date对象格式化为指定格式的字符串
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            String formattedNewDate = LocalDateTime.ofInstant(newDate.toInstant(), ZoneId.systemDefault()).format(formatter);
            // 使用SimpleDateFormat类将字符串转换为Date对象
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date expirationTime = null;
            try {
                expirationTime = sdf.parse(formattedNewDate);
            } catch (Exception e) {
                e.printStackTrace();
            }
            System.out.println(expirationTime + "===================");

            // 调用setExpirationTime方法
            userVip.setExpirationTime(expirationTime);
            System.out.println(formattedNewDate);

        }
        userVipService.upd(userVip);
        UserVip userVip2 = new UserVip();
        userVip2.setUserId(Integer.valueOf(userLoginId));
        return userVipService.findObjectByPramas(userVip2);




    }

//    @Scheduled(cron = "0 0/30 * * * ?")
//    public void updateVipTimes() throws Exception {
//        List<UserVip> userVipList = userVipService.findAll();
//        for (UserVip userVip : userVipList){
//            Date expirTime = userVip.getExpirationTime();
//            Date now = new Date(System.currentTimeMillis());
//
//            if (expirTime.compareTo(now) > 0) {
//                // 会员未过期
//
//            } else {
//                // 会员已过期
//                UserVip userVip1 = new UserVip();
//                userVip1.setVipRank("0");
//                userVip1.setId(userVip.getId());
//                userVip1.setGptTimes("3");
//                userVip1.setInfoUpdTimes("1");
//                userVip1.setProbabilityTimes("1");
//                userVipService.upd(userVip1);
//            }
//        }
//    }

    /**
     * 修改测录取率次数
     */
    @RequestMapping("/updProbabilityTimes")
    @ResponseBody
    public Result updProbabilityTimes(HttpServletRequest request) throws Exception {

        UserLogin userLogin = ResolveTokenUtil.targetLogin(request.getHeader("token"));
        UserLogin targetUser = userLoginService.findObjectByPramas(userLogin);
        UserVip userVip = new UserVip();
        userVip.setUserId(targetUser.getId());
        UserVip targetVip = userVipService.findObjectByPramas(userVip);


        HashMap<String, Object> map = new HashMap<>();


        if(targetVip.getProbabilityTimes().equals("NaN")){
            targetVip.setProbabilityTimes("50");
        }
        if(targetVip.getProbabilityTimes().equals("0")){
            map.put("ProbabilityTimes","0");
            return new Result(map,SUCCESSCODE);
        }

        int probabilityTimes = Integer.parseInt(targetVip.getProbabilityTimes());
        probabilityTimes-=1;
        UserVip userVip1 = new UserVip();
        userVip1.setUserId(targetUser.getId());
        userVip1.setProbabilityTimes(String.valueOf(probabilityTimes));
        userVipService.upd(userVip1);
        map.put("ProbabilityTimes",probabilityTimes);
        return new Result(map,SUCCESSCODE);

    }


    /**
     * 修改gpt次数
     */
    @RequestMapping("/updGptTimes")
    @ResponseBody
    public UserVip updGptTimes(HttpServletRequest request) throws Exception {
        UserLogin userLogin = ResolveTokenUtil.targetLogin(request.getHeader("token"));
        UserLogin targetUser = userLoginService.findObjectByPramas(userLogin);
        UserVip userVip = new UserVip();
        userVip.setUserId(targetUser.getId());
        UserVip targetVip = userVipService.findObjectByPramas(userVip);

        String gptTimes = targetVip.getGptTimes();
        if (gptTimes == null || gptTimes.equals("NaN")){
            gptTimes = "30";
        }else{
            UserVip userVip1 = new UserVip();
            userVip1.setUserId(targetVip.getUserId());
            userVip1.setGptTimes(String.valueOf(Integer.valueOf(gptTimes) - 1));
            userVipService.upd(userVip1);
        }
        UserVip userVip2 = new UserVip();
        userVip2.setUserId(targetUser.getId());
        return userVipService.findObjectByPramas(userVip2);
    }

}
